package com.hd.crdao.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.bean.CheckInfoBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.StringUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Programming
 *@date 2017/7/11 0011
 */
public class TodayCarCheckActivity extends BaseSecondActivity {


    @BindView(R.id.todaycarcheck_head)
    ExpandHeadView mTodaycarcheckHead;
    @BindView(R.id.takePicture)
    TextView takePicture;
    @BindView(R.id.beizhu)
    TextView beizhu;


    @BindView(R.id.tvDate)
    TextView mTvDate;
    @BindView(R.id.reviewphoto)
    ImageView mReviewphoto;
    @BindView(R.id.display_result)
    LinearLayout mDisplayResult;
    @BindView(R.id.remarks)
    TextView mRemarks;
    @BindView(R.id.noremarks)
    LinearLayout mNoRemarks;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    public CheckInfoBean checkInfoBean;

    @Override
    protected int setContentView() {
        return R.layout.activity_todaycarcheck;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mTodaycarcheckHead;
    }

    @Override
    protected void initView() {
        initData();
        mTodaycarcheckHead.getHeadViewRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UIUtils.getContext(), CarCheckRecordActivity.class));
            }
        });
        initBaiduLocation();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        String vehicleId = getIntent().getStringExtra("vehicleId") + "";
        if(!TextUtils.isEmpty(vehicleId)){
            SPUtils.saveString("vehicleId",vehicleId);
        }
        OkHttpUtils.post().url(Constants.GETCHECKINFOBYUSER_URL)
                .addParams("sign", Constants.SIGN)
                .addParams("userId", SPUtils.getString(Config.userId, ""))
                .addParams("vehicleId", vehicleId)

                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int success = Integer.parseInt(jsonObject.getString("success"));
                    String message = jsonObject.getString("message");
                    int checkCode = Integer.parseInt(jsonObject.getString("checkCode"));
                    if (success == 0) {
                        Object checkinfo = jsonObject.get("checkInfo");
                        if (checkinfo instanceof String) {
                            mDisplayResult.setVisibility(View.GONE);
                        } else {
                            String checkInfo = jsonObject.getString("checkInfo");
                            checkInfoBean = new Gson().fromJson(checkInfo, CheckInfoBean.class);

                            if (checkCode == 0) {
                                mDisplayResult.setVisibility(View.GONE);
                            } else if (checkCode == 1) {        //备注
                                mDisplayResult.setVisibility(View.VISIBLE);
                                mNoRemarks.setVisibility(View.GONE);

                                String dateWithoutYear = StringUtils.getDateWithoutYear(checkInfoBean.getClDate());
                                  mTvDate.setText(dateWithoutYear);
                                mRemarks.setText(checkInfoBean.getRemarks());
                            } else if (checkCode == 2) {        //核查(照片)
                                mDisplayResult.setVisibility(View.VISIBLE);
                                mNoRemarks.setVisibility(View.VISIBLE);
                                mTvDate.setText(checkInfoBean.getClDate());
                                mReviewphoto.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(UIUtils.getContext(), SwitchImageActivity.class);
                                        String[] paths = new String[2];
                                        List<CheckInfoBean.PicStoresBean> picStores = checkInfoBean.getPicStores();
                                        if (picStores != null) {
                                            paths[0] = picStores.get(0).getPsPath();
                                            paths[1] = picStores.get(1).getPsPath();
                                        } else {
                                            paths[0] = "";
                                            paths[1] = "";
                                        }
                                        intent.putExtra("imagepath", paths);
                                        startActivity(intent);
                                    }
                                });
                            }


                        }
                    } else {
                        MyToast.show(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    private void initBaiduLocation() {
        mLocationClient = new LocationClient(UIUtils.getContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        initLocation();
        mLocationClient.start();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }

    @OnClick({R.id.takePicture, R.id.beizhu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.takePicture:
                startActivity(new Intent(UIUtils.getContext(), CarCheckPhotoActivity.class));
                break;
            case R.id.beizhu:
                Intent intent = new Intent(UIUtils.getContext(), CommentActivity.class);
                startActivity(intent);
                break;

        }
    }


    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            String latLon = location.getLongitude()+ "," + location.getLatitude() ;
            SPUtils.saveString("latLon", latLon);
            mLocationClient.stop();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }
}
